//
//  ChangePwdViewController.m
//  LocomotiveGuards
//
//  Created by zwj on 15-11-30.
//  Copyright (c) 2015年 REDOOR. All rights reserved.
//

#import "ChangePwdViewController.h"
#import "PopLoadMsg.h"
#import "PopMsg.h"
#import "LoginViewController.h"
#import "AlertView.h"

@interface ChangePwdViewController () <UITextFieldDelegate>
{
    UITextField *_fieldOldPwd;
    UITextField *_fieldNewPwd;
    UITextField *_fieldConfirmPwd;
    NSString *message;
}
@property (nonatomic, strong) NSString *userOrTourist;

@end

@implementation ChangePwdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.userOrTourist = [[NSUserDefaults standardUserDefaults] objectForKey:@"userOrTourist"];

    [self createMyNav];
    [self configView];
}

- (void)createMyNav
{
    [self addTitle:@"修改密码" imageName:@"changepassword"];
    [self addBackBtnTarget:self action:@selector(backBtnClick)];
}

- (void)configView
{
    NSArray *pwdArray = @[@"旧密码",@"新密码",@"确认密码"];
    for (NSInteger i=0; i<3; i++) {
        UILabel *pwdLabel = [self createLabelFrame:CGRectMake(25*W, 20+64*H+50*H*i, 60*W, 35*H) title:pwdArray[i] font:[UIFont systemFontOfSize:15]];
        pwdLabel.textAlignment = NSTextAlignmentLeft;
        pwdLabel.textColor = [UIColor grayColor];
        [self.view addSubview:pwdLabel];
        
        UITextField *inputFiled = [self createTextFieldFrame:CGRectMake(95*W, 20+64*H+50*H*i, 200*W, 35*H) title:nil placeholder:@"输入6-12位字母或数字"];
        NSAttributedString *attri = [[NSAttributedString alloc] initWithString:inputFiled.placeholder attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}];
        inputFiled.attributedPlaceholder = attri;
        [inputFiled setBackground:[UIImage imageNamed:@"changepassword_input"]];
        inputFiled.borderStyle = UITextBorderStyleNone;
        inputFiled.returnKeyType = UIReturnKeyDone;
        inputFiled.secureTextEntry = YES;
        inputFiled.tag = 100+i;
        [self.view addSubview:inputFiled];
    }
    
    UIButton *confirmBtn = [self createBtnFrame:CGRectMake((SCREEN_WIDTH-104*W)/2, 20+64*H+50*H*3+10*H, 104*W, 34*H) title:nil bgImageName:@"update_acknowledge_password" selectedImageName:@"update_acknowledge_password_on" target:self action:@selector(confirmBtnClicked)];
    [self.view addSubview:confirmBtn];
    
    _fieldOldPwd = (UITextField *)[self.view viewWithTag:100];
    _fieldOldPwd.delegate = self;
    _fieldNewPwd = (UITextField *)[self.view viewWithTag:101];
    _fieldNewPwd.delegate = self;
    _fieldConfirmPwd = (UITextField *)[self.view viewWithTag:102];
    _fieldConfirmPwd.delegate = self;
}

#pragma mark - 网络请求
//重置密码请求
- (void)resetPwdRequest
{
    PopLoadMsg *loadmsg = [PopLoadMsg new];
    [loadmsg delayLoadImages];
    
    NSDictionary *paramdic = @{@"loginId":[[NSUserDefaults standardUserDefaults] objectForKey:@"phonenumber"],
                             @"oldPwd":_fieldOldPwd.text,
                             @"newPwd":_fieldNewPwd.text};
    NSString *url = [urlstring stringByAppendingString:@"resetPwd.do"];
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:paramdic success:^(AFHTTPRequestOperation *op,id responseObject){
        [loadmsg delayImagesRemove];
        NSDictionary *dic = (NSDictionary *)responseObject;
        NSLog(@"dic = %@", dic);
        NSInteger flag = [[dic objectForKey:@"flag"] integerValue];
        message = [dic objectForKey:@"msg"];

        if (flag == 0) {
            NSLog(@"Reset Success!");
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"操作已成功！" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
            [alert show];
        }
        else {
            [PopMsg showMessage:message Lasttime:1.0f];
        }
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        [loadmsg delayImagesRemove];
        [PopMsg showMessage:@"网络异常，请重试" Lasttime:1.0f];
    }];
}

#pragma mark - 点击事件
- (void)backBtnClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)confirmBtnClicked
{
    if ([self.userOrTourist isEqualToString:@"1"]) {
        if (_fieldOldPwd.text.length >= 6 && _fieldOldPwd.text.length <= 12 &&
            _fieldNewPwd.text.length >= 6 && _fieldNewPwd.text.length <= 12 &&
            _fieldConfirmPwd.text.length >= 6 && _fieldConfirmPwd.text.length <= 12 &&
            [_fieldNewPwd.text isEqualToString:_fieldConfirmPwd.text])
        {
            message = nil;
            [self resetPwdRequest];
        }
        else
        {
            message = nil;
            int i = [self checkIsHaveNumAndLetter:_fieldOldPwd.text];
            int j = [self checkIsHaveNumAndLetter:_fieldNewPwd.text];
            int k = [self checkIsHaveNumAndLetter:_fieldConfirmPwd.text];
            
            if (![_fieldNewPwd.text isEqualToString:_fieldConfirmPwd.text]) {
                message = @"新密码与确认密码输入不一致";
            }
            
            if(k==0){
                message = @"确认密码必须包括大小写字母和数字";
            }
            
            if (_fieldConfirmPwd.text.length > 12) {
                message = @"确认密码高于12位";
            }
            
            if (_fieldConfirmPwd.text.length < 6) {
                message = @"确认密码低于6位";
            }
            
            if (_fieldConfirmPwd.text.length == 0) {
                message = @"确认密码为空";
            }
            
            if(j==0){
                message = @"新密码必须包括大小写字母和数字";
            }
            
            if (_fieldNewPwd.text.length > 12) {
                message = @"新密码高于12位";
            }
            
            if (_fieldNewPwd.text.length < 6) {
                message = @"新密码低于6位";
            }
            
            if (_fieldNewPwd.text.length == 0) {
                message = @"新密码为空";
            }
            
            if(i==0){
                message = @"旧密码必须包括大小写字母和数字";
            }
            
            if (_fieldOldPwd.text.length > 12) {
                message = @"旧密码高于12位";
            }
            
            if (_fieldOldPwd.text.length < 6) {
                message = @"旧密码低于6位";
            }
            
            if (_fieldOldPwd.text.length == 0) {
                message = @"旧密码为空";
            }
            
            if (message) {
                [PopMsg showMessage:message Lasttime:1.0f];
            }
        }

    }
    else {
        AlertView *alertView = [[AlertView alloc] initWithConfirmButtonBlock:^{
            NSLog(@"登录");
            LoginViewController *loginVC = [[LoginViewController alloc]init];
            [self presentViewController:loginVC animated:YES completion:nil];
        } cancelButtonBlock:^{
            NSLog(@"取消");
        }];
        [self.view addSubview:alertView];
    }
}

//收起键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_fieldOldPwd resignFirstResponder];
    [_fieldNewPwd resignFirstResponder];
    [_fieldConfirmPwd resignFirstResponder];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_fieldOldPwd resignFirstResponder];
    [_fieldNewPwd resignFirstResponder];
    [_fieldConfirmPwd resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:kAlphaNum] invertedSet];
    
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; //按cs分离出数组,数组按@""分离出字符串
    
    BOOL canChange = [string isEqualToString:filtered];
    
    return canChange;
}

- (int)checkIsHaveNumAndLetter:(NSString*)pPassword{
    //數字條件
    NSRegularExpression *tNumRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[0-9]" options:NSRegularExpressionCaseInsensitive error:nil];
    
    //符合數字條件的有幾個字元
    int tNumMatchCount = [tNumRegularExpression numberOfMatchesInString:pPassword
                                                                options:NSMatchingReportProgress
                                                                  range:NSMakeRange(0, pPassword.length)];
    
    //大写字母條件
    NSRegularExpression *tLetterRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[A-Z]" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
    
    //符合大写字母條件的有幾個字元
    int tLetterMatchCount = [tLetterRegularExpression numberOfMatchesInString:pPassword options:NSMatchingReportProgress range:NSMakeRange(0, pPassword.length)];
    
    
    //小写字母條件
    NSRegularExpression *littleLetterRegularExpression = [NSRegularExpression regularExpressionWithPattern:@"[a-z]" options:NSRegularExpressionAllowCommentsAndWhitespace error:nil];
    
    //符合小写字母條件的有幾個字元
    int littleLetterMatchCount = [littleLetterRegularExpression numberOfMatchesInString:pPassword options:NSMatchingReportProgress range:NSMakeRange(0, pPassword.length)];
    
    
    if (tNumMatchCount == pPassword.length)
    {
        //全部符合數字，表示沒有英文
        return 0;
    }
    else if (tLetterMatchCount == pPassword.length)
    {
        //全部符合大写字母，表示沒有數字
        return 0;
    }
    else if(littleLetterMatchCount==pPassword.length){
        //全部符合小写字母，表示沒有數字
        return 0;
    }
    else if (tNumMatchCount + tLetterMatchCount == pPassword.length)
    {
        //数字和大写字母相加为密码长度，表示没有小写字母
        return 0;
    }
    else if (tNumMatchCount + littleLetterMatchCount == pPassword.length)
    {
        //数字和小写字母相加为密码长度，表示没有大写字母
        return 0;
    }
    else if (littleLetterMatchCount + tLetterMatchCount == pPassword.length)
    {
        //小写字母和大写字母相加为密码长度，表示没有数字
        return 0;
    }
    else
    {
        return 1;
        //可能包含標點符號的情況，或是包含非英文的文字，這裡再依照需求詳細判斷想呈現的錯誤
    }
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
